package com.bt.lms.ui.action.course;

import com.alibaba.fastjson.JSON;
import com.bt.lms.constants.CourseBizTypeConstant;
import com.bt.lms.entity.CourseInfo;
import com.bt.lms.network.msg.ReqMsg;
import com.bt.lms.network.msg.RespMsg;
import com.bt.lms.ui.action.course.vo.SearchCourseVo;
import com.bt.lms.ui.page.course.CourseInfoList;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.scene.control.Alert;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextField;
import org.apache.commons.beanutils.BeanUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.Socket;

/**
 * 课程信息条件搜索按钮
 *
 * @author 李鹏
 */
public class SearchBtnAction implements EventHandler {

    /**
     * 课程信息界面
     */
    private CourseInfoList courseInfoList;

    public SearchBtnAction(CourseInfoList courseInfoList) {
        this.courseInfoList = courseInfoList;
    }

    @Override
    public void handle(Event event) {

        //1.获取用户输入，返回VO：里面承载着用户的输入
        SearchCourseVo searchCourseVo = getInParams();//获取参数
        //2.验证用户输入
        String validateMsg = validateInParam(searchCourseVo);
        //3.组包（根据自定义的网络消息协议），inP:VO outP:消息
        byte[] bytes = null;
        if (null == validateMsg) {

            //验证通过，组包
            bytes = handle2ReqMsg(searchCourseVo);

        } else {
            //提示，程序终止
            return;
        }

        //4.组网（根据咱们自定义的网络连接交互规范来定义）inP:服务器的信息（ip,port....）
        Socket socket = getNet();
        //5.发送消息，inP:消息 ouP:是否发送成熟
        boolean flag = send(socket, bytes);
    }


    /**
     * 发送信息
     * 1.将消息转为字节流
     * 2.发送
     *
     * @param socket 发送的socket
     * @param bytes  要发送的消息
     * @return
     */
    private boolean send(Socket socket, byte[] bytes) {

        try {
            //发送消息
            OutputStream outputStream = socket.getOutputStream();
            outputStream.write(bytes); //写
            outputStream.flush();//冲刷

            //接收回应信息
            InputStream in = socket.getInputStream();
            byte[] buf = new byte[1024];
            in.read(buf); //读
            RespMsg respMsg = RespMsg.toRespMsg(buf);
            String data = respMsg.getData();

        } catch (IOException e) {
//            throw new RuntimeException(e);
        }

        return true;
    }

    /**
     * 获取网络
     *
     * @return socket
     */
    private Socket getNet() {

        String serverIp = "127.0.0.1";
        int serverPort = 8888;
        Socket socket = null;

        try {
            socket = new Socket(serverIp, serverPort);
        } catch (IOException e) {
//            throw new RuntimeException(e);
            return null;
        }

        return socket;
    }


    /**
     * 将用户输入的信息处理成我们规定的请求信息
     * 组包
     *
     * @param searchCourseVo 用户输入
     * @return 请求消息
     */
    private byte[] handle2ReqMsg(SearchCourseVo searchCourseVo) {
        //消息
        ReqMsg reqMsg = new ReqMsg();

        //课程信息
        CourseInfo courseInfo = new CourseInfo();

        //业务类型
        reqMsg.setBizType(CourseBizTypeConstant.COURSE_PAGE_CONDITION_QUERY);

        //vo转entity(目标，源)
        try {
            BeanUtils.copyProperties(courseInfo, searchCourseVo);

            String courseStr = JSON.toJSONString(searchCourseVo);
            //数据带走
            reqMsg.setData(courseStr);

        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
        byte[] bytes = reqMsg.toBytes();

        return bytes;
    }

    private String validateInParam(SearchCourseVo searchCourseVo) {

        String msg = ""; //所有提示信息

        String courseNumber = searchCourseVo.getCode();//课程编号
        String numberBlankMsg = "课程编号必须填写！\r\n";
        String numberLengthMsg = "课程编号长度在18位以下，包含18！\r\n";
        if ("".equals(courseNumber)) {
            msg += numberBlankMsg;
        } else {
            if (courseNumber.length() > 18) {
                msg += numberLengthMsg;
            }
        }

        //处理返回
        if ("".equals(msg)) {
            msg = null;
        }
        if (!(msg == null)) {
            Alert alert = new Alert(Alert.AlertType.WARNING);
            alert.setContentText(msg);
            alert.show();

            return null;
        }

        return msg;
    }

    /**
     * 获取用户输入
     *
     * @return 课程分页条件
     */
    private SearchCourseVo getInParams() {
        //VO对象
        SearchCourseVo searchCourseVo = new SearchCourseVo();

        //所属的学习中心
        ComboBox studyCenterCB = (ComboBox) courseInfoList.lookup("#studyCenterCB");
        String studyCenter = (String) studyCenterCB.getValue();
        Integer studyCenterLevel = -1;
        switch (studyCenter) {
            case "北京师范大学":
                studyCenterLevel = 1;
                break;
            case "东北师范大学":
                studyCenterLevel = 2;
                break;
            case "西南大学":
                studyCenterLevel = 3;
                break;
        }
        searchCourseVo.setStudyCenter(studyCenterLevel);

        //适合层次
        ComboBox applyLevelComboBox = (ComboBox) courseInfoList.lookup("#applyLevelComboBox");
        //获取适合层次输入
        String value = (String) applyLevelComboBox.getValue();
        Integer level = -1;
        switch (value) {
            case "高中":
                level = 1;
                break;
            case "大专":
                level = 2;
                break;
            case "本科":
                level = 3;
                break;
            case "其他":
                level = 4;
                break;
        }
        searchCourseVo.setApplyLevel(level);

        //课程编号
        TextField codeSearchTF = (TextField) courseInfoList.lookup("#codeSearchTF");
        //获取课程编号输入
        String code = codeSearchTF.getText().trim();
        searchCourseVo.setCode(code);

        return searchCourseVo;
    }
}
